package cn.appkf.flappybird.stage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.ProgressBar;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Touchpad;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.test.TestGame;

import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cn.appkf.flappybird.actor.BarActor;
import cn.appkf.flappybird.actor.MyActor;
import cn.appkf.flappybird.actor.Skill;
import cn.appkf.flappybird.net.NetWorker;
import cn.appkf.flappybird.res.Res;
import cn.appkf.flappybird.stage.base.TBaseStage;
import cn.appkf.flappybird.ui.JumpButton;
import cn.appkf.flappybird.ui.MyMap;
import sun.rmi.runtime.Log;

/**
 * Created by Administrator on 2016/7/27.
 */
public class TestStage extends TBaseStage {



    public static TiledMap map;
    public static MyMap mymap;
    OrthogonalTiledMapRenderer render;
    OrthographicCamera cam;

    MyActor actor;
    Touchpad touchpad;

    NetWorker netWorker;

    AssetManager manager = new AssetManager();


    private List<Skill> skillList=new ArrayList<Skill>();

    private Map<String,MyActor> players=new HashMap<String,MyActor>();


    private Touchpad.TouchpadStyle touchpadStyle;
    private Skin touchpadSkin;
    private Drawable touchBackground;
    private Drawable touchKnob;

    private ProgressBar hpBar;


    float cx=30;
    float cy=30;



    public static final String A_DOCIN="actor/docin.png";
    public static final String A_FACE1="actor/face1.png";
    public static final String A_WALK_SEE="actor/walk_see.png";
    public static final String A_WALK_SEE2="actor/walk_see2.png";


    public TestStage(TestGame mainGame, Viewport viewport) {
        super(mainGame, viewport);

        manager.load(A_DOCIN, Texture.class);
        manager.load(A_FACE1, Texture.class);
        manager.load(A_WALK_SEE, Texture.class);
        manager.load(A_WALK_SEE2, Texture.class);

        manager.finishLoading();

        init();
    }



    public void getMsg(String msg){

        JSONObject jo=JSON.parseObject(msg);

        if(jo.getString("id")!=null&&jo.getString("id").equals(actor.getID())){
            return;
        }

        if(jo.getString("type").equals("move")){

            Gdx.app.debug("MyTag",msg);

            MyActor player= players.get(jo.getString("id"));
            if(jo.getInteger("move")==MyActor.STAY_LEFT){
                player.setMoveLeft(true);
                player.setMoveRight(false);
            }else if(jo.getInteger("move")==MyActor.STAY_RIGHT){
                player.setMoveLeft(false);
                player.setMoveRight(true);
            }else{
                player.setMoveLeft(false);
                player.setMoveRight(false);
            }


        }else if(jo.getString("type").equals("skill")){
            MyActor player= players.get(jo.getString("id"));
            Skill s=player.doSkill();
            getRoot().addActorBefore(actor,s);
            skillList.add(s);
        }else if(jo.getString("type").equals("push")){


                newActor(jo);


        }else  if(jo.getString("type").equals("players")){

            Iterator<Object> players=jo.getJSONArray("players").iterator();
            while (players.hasNext()){
                JSONObject pp=(JSONObject) players.next();
                newActor(pp);
            }

        }else if(jo.getString("type").equals("jump")){
            players.get(jo.getString("id")).jump();
        }

    }


    public void newActor(JSONObject jo){

        if(jo.getString("id").equals(actor.getID())){
            return;
        }
        MyActor actor2=new MyActor(mymap,manager,netWorker);
        players.put(jo.getString("id"),actor2);
        JSONObject actor=jo.getJSONObject("actor");
        //actor2.setPosition(0, 20);     // 或者 setX(), setY() 分开设置
        actor2.setMapX(actor.getFloat("MapX"));
        actor2.setMapY(actor.getFloat("MapY"));

        // 设置演员 旋转和缩放支点 为演员的左下角
        actor2.setOrigin(0, 0);

        // 设置演员缩放比, X 轴方向缩小到 0.5 倍, Y 轴方向保持不变
        actor2.setScale(1.0F, 1.0F);

        actor2.setOther(true);
        actor2.setID(jo.getString("id"));

        getRoot().addActorBefore(this.actor,actor2);
    }



    public void init(){

//        socket=new Socket()

        netWorker=new NetWorker("192.168.0.148",7104,this);



        Skin touchpadSkin = new Skin();

        touchpadSkin.add("touchBackground", new Texture(Gdx.files.internal("touchPad/background.png")));
        //Set knob image
        touchpadSkin.add("touchKnob", new Texture(Gdx.files.internal("touchPad/knob.png")));

         touchpadStyle = new Touchpad.TouchpadStyle();
        //Create Drawable's from TouchPad skin
        touchBackground = touchpadSkin.getDrawable("touchBackground");
        touchKnob = touchpadSkin.getDrawable("touchKnob");
        //Apply the Drawables to the TouchPad Style
        touchpadStyle.background = touchBackground;
        touchpadStyle.knob = touchKnob;


         touchpad = new Touchpad(1f, touchpadStyle);

        touchpad.setSize(100,100);

        touchpad.setPosition(20, 20);



        this.map=new TmxMapLoader().load("atlas/floor.tmx");

        mymap=new MyMap();
        mymap.setTiledMap(map);
        mymap.init();


        cam = new OrthographicCamera(getWidth(),getHeight());
        render = new OrthogonalTiledMapRenderer(map);





        cam.setToOrtho(false,getWidth(),getHeight());
        cam.position.x=cam.viewportWidth/2;
        cam.position.y=cam.viewportHeight/2;
        cam.update();

        render.setView(cam);

        mymap.setCam(cam);

        // 创建纹理, badlogic.jpg 图片的宽高为 256 * 256

        // 创建演员
        actor = new MyActor(mymap,manager,netWorker);

        /* 设置演员属性的值 */

        // 设置演员的坐标
        actor.setPosition(0, 20);     // 或者 setX(), setY() 分开设置
        actor.setMapX(20);
        actor.setMapY(50);

        // 设置演员 旋转和缩放支点 为演员的左下角
        actor.setOrigin(0, 0);

        // 设置演员缩放比, X 轴方向缩小到 0.5 倍, Y 轴方向保持不变
        actor.setScale(1.0F, 1.0F);


        actor.setID("actor7104");

        this.addActor(actor);



        new Thread(netWorker).start();




/*        MyActor actor2=new MyActor(new TextureRegion(texture),mymap);
        players.put("lalala",actor2);

        actor2.setPosition(0, 20);     // 或者 setX(), setY() 分开设置
        actor2.setMapX(100);
        actor2.setMapY(100);

        // 设置演员 旋转和缩放支点 为演员的左下角
        actor2.setOrigin(0, 0);

        // 设置演员缩放比, X 轴方向缩小到 0.5 倍, Y 轴方向保持不变
        actor2.setScale(1.0F, 1.0F);

        actor2.setOther(true);
        addActor(actor2);*/




        Texture upTexture = new Texture(Gdx.files.internal("button/btn_jump.png"));
        Texture downTexture = new Texture(Gdx.files.internal("button/btn2_jump.png"));

        Texture upTexture2 = new Texture(Gdx.files.internal("button/face1.png"));
        Texture downTexture2 = new Texture(Gdx.files.internal("button/face2.png"));

        /*
         * 第 2 步: 创建 ButtonStyle
         */
        Button.ButtonStyle style = new Button.ButtonStyle();
        Button.ButtonStyle style2 = new Button.ButtonStyle();

        // 设置 style 的 弹起 和 按下 状态的纹理区域
        style.up = new TextureRegionDrawable(new TextureRegion(upTexture));
        style.down = new TextureRegionDrawable(new TextureRegion(downTexture));

        style2.up = new TextureRegionDrawable(new TextureRegion(upTexture2));
        style2.down = new TextureRegionDrawable(new TextureRegion(downTexture2));


        JumpButton button=new JumpButton(style);
        JumpButton button2=new JumpButton(style2);


        button.setVisible(true);
        button2.setVisible(true);

        button.setPosition(400, 20);
        button2.setPosition(330, 20);
        button.addListener(new ClickListener() {

            @Override
            public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
                actor.jump();
                JSONObject jo=new JSONObject();
                jo.put("id",actor.getID());
                jo.put("type","jump");
                netWorker.send(jo.toString());
                return super.touchDown(event, x, y, pointer, button);
            }

            @Override
            public void clicked(InputEvent event, float x, float y) {
//                actor.setVelocityY(Res.Physics.JUMP_VELOCITY);
                Gdx.app.log("Tag", "按钮被点击了");
            }
        });

        button2.addListener(new ClickListener(){
            @Override
            public void clicked(InputEvent event, float x, float y) {
                super.clicked(event, x, y);

                Skill s=actor.doSkill();
                addActor(s);
                skillList.add(s);
            }
        });

        this.addActor(button);
        this.addActor(button2);
        addActor(touchpad);



    }


    @Override
    public void act(float delta) {
        super.act(delta);


        if(touchpad.getKnobPercentX()>0){
            actor.setMoveLeft(false);
            actor.setMoveRight(true);
        }else  if(touchpad.getKnobPercentX()<0){
            actor.setMoveRight(false);
            actor.setMoveLeft(true);
        }else{
            actor.setMoveLeft(false);
            actor.setMoveRight(false);
        }

        if(touchpad.getKnobPercentY()>0){
            actor.setMoveUp(true);
            actor.setMoveDown(false);
        }else if(touchpad.getKnobPercentY()<0){
            actor.setMoveDown(true);
            actor.setMoveUp(false);
        }else{
            actor.setMoveDown(false);
            actor.setMoveUp(false);
        }



        if(actor.getMapX()<cam.viewportWidth/2){
            actor.setX(actor.getMapX());
        }else if(actor.getMapX()>mymap.getMapWidth()-cam.viewportWidth/2){
            actor.setX(actor.getMapX()-mymap.getMapWidth()+cam.viewportWidth);
        }else{
            cam.position.x = actor.getMapX();
        }

        if(actor.getMapY()>mymap.getMapHeight()-cam.viewportHeight / 2) {
            actor.setY(actor.getMapY()+cam.viewportHeight-mymap.getMapHeight());
        }else if(actor.getMapY()<cam.viewportHeight/2){
            actor.setY(actor.getMapY());
        }else{
            cam.position.y = actor.getMapY();
        }

        checkSkill();

    }


    public MyActor getActor() {
        return actor;
    }

    public void checkSkill(){
        Iterator<Skill> it = skillList.iterator();
        Skill skill = null;
        while (it.hasNext()) {
            skill = it.next();
            if (skill.isDown()) {
                // 从舞台中移除水管
                getRoot().removeActor(skill);
                // 从集合中移除水管
                it.remove();
                // 回收水管对象(放回到对象池中)
            }else{
                Iterator<MyActor> pp= this.players.values().iterator();
                while (pp.hasNext()){
                    skill.checkAffect(pp.next());
                }
                skill.checkAffect(actor);

            }
        }
    }

    @Override
    public void draw() {
        cam.update();
        render.setView(cam);
        render.render();
        super.draw();

    }


    public static MyMap getMymap() {
        return mymap;
    }

    public static void setMymap(MyMap mymap) {
        TestStage.mymap = mymap;
    }

    public OrthographicCamera getCam() {
        return cam;
    }

    public void setCam(OrthographicCamera cam) {
        this.cam = cam;
    }

    public void setActor(MyActor actor) {
        this.actor = actor;
    }

    public AssetManager getManager() {
        return manager;
    }

    public void setManager(AssetManager manager) {
        this.manager = manager;
    }
}
